<!doctype html>



  


<html class="theme-next pisces use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Hexo, NexT" />





  <link rel="alternate" href="/atom.xml" title="liujinlongxa的技术博客" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="##关于多线程编程
###什么是多线程简单的来说，并发应用程序中一个单独的执行路径，就是一个线程。
###相关术语

进程：用于指代一个正在运行的可执行程序，它可以包含多个线程。
任务：用于指代抽象的概念，表示需要执行工作。
线程的同步：同步就是协同步调，按预定的先后次序进行运行。线程的同步即一个线程执行完指定操作后，另个一个线程再执行。
线程的互斥：线程互斥是指某一资源同时只允许一个访问者对其进">
<meta property="og:type" content="article">
<meta property="og:title" content="iOS中的多线程编程">
<meta property="og:url" content="http://yoursite.com/2015/10/04/iOS中的多线程编程/index.html">
<meta property="og:site_name" content="liujinlongxa的技术博客">
<meta property="og:description" content="##关于多线程编程
###什么是多线程简单的来说，并发应用程序中一个单独的执行路径，就是一个线程。
###相关术语

进程：用于指代一个正在运行的可执行程序，它可以包含多个线程。
任务：用于指代抽象的概念，表示需要执行工作。
线程的同步：同步就是协同步调，按预定的先后次序进行运行。线程的同步即一个线程执行完指定操作后，另个一个线程再执行。
线程的互斥：线程互斥是指某一资源同时只允许一个访问者对其进">
<meta property="og:image" content="http://img.blog.csdn.net/20150410103408108">
<meta property="og:image" content="http://img.blog.csdn.net/20150410104742410">
<meta property="og:updated_time" content="2016-07-01T12:43:36.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="iOS中的多线程编程">
<meta name="twitter:description" content="##关于多线程编程
###什么是多线程简单的来说，并发应用程序中一个单独的执行路径，就是一个线程。
###相关术语

进程：用于指代一个正在运行的可执行程序，它可以包含多个线程。
任务：用于指代抽象的概念，表示需要执行工作。
线程的同步：同步就是协同步调，按预定的先后次序进行运行。线程的同步即一个线程执行完指定操作后，另个一个线程再执行。
线程的互斥：线程互斥是指某一资源同时只允许一个访问者对其进">
<meta name="twitter:image" content="http://img.blog.csdn.net/20150410103408108">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 0,
      author: '博主'
    }
  };
</script>




  <link rel="canonical" href="http://yoursite.com/2015/10/04/iOS中的多线程编程/"/>

  <title> iOS中的多线程编程 | liujinlongxa的技术博客 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">liujinlongxa的技术博客</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle"></p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                iOS中的多线程编程
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2015-10-04T00:00:00+08:00" content="2015-10-04">
              2015-10-04
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/iOS开发/" itemprop="url" rel="index">
                    <span itemprop="name">iOS开发</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2015/10/04/iOS中的多线程编程/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="2015/10/04/iOS中的多线程编程/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>##关于多线程编程</p>
<p>###什么是多线程<br>简单的来说，并发应用程序中一个单独的执行路径，就是一个线程。</p>
<p>###相关术语</p>
<ul>
<li>进程：用于指代一个正在运行的可执行程序，它可以包含多个线程。</li>
<li>任务：用于指代抽象的概念，表示需要执行工作。</li>
<li>线程的同步：同步就是协同步调，按预定的先后次序进行运行。线程的同步即一个线程执行完指定操作后，另个一个线程再执行。</li>
<li>线程的互斥：线程互斥是指某一资源同时只允许一个访问者对其进行访问，具有唯一性和排它性。<br>###iOS中的多线程编程</li>
<li>pthread（POSIX threads）：一套C语言接口，定义了创建和管理线程的API，非常灵活，可以直接操作线程。</li>
<li>NSThread：一套OC接口，需要自己手动管理线程，比GCD和NSOperation更加轻量级。</li>
<li>GCD：是iOS4出的一套并发编程的接口，纯C语言接口。以队列为基础。</li>
<li>NSOperation：一套面向对象的OC API，不需要手动管理线程。能实现一些GCD实现不了的功能。</li>
</ul>
<p>##NSThread</p>
<p>###基本操作</p>
<p>####线程的创建</p>
<ul>
<li><p>类方法创建线程</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">[<span class="built_in">NSThread</span> detachNewThreadSelector:<span class="keyword">@selector</span>(threadFun:) toTarget:<span class="keyword">self</span> withObject:<span class="string">@"helloworld"</span>];</div></pre></td></tr></table></figure>
</li>
<li><p>实例方法创建线程</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="built_in">NSThread</span> * th = [[<span class="built_in">NSThread</span> alloc] initWithTarget:<span class="keyword">self</span> selector:<span class="keyword">@selector</span>(threadFun:) object:<span class="string">@"helloworld"</span>];</div><div class="line">    [th start];</div></pre></td></tr></table></figure>
</li>
<li><p>继承NSThread，重写main方法(与NSOperation类似)</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//MyThread.h</span></div><div class="line"><span class="class"><span class="keyword">@interface</span> <span class="title">MyThread</span> : <span class="title">NSThread</span></span></div><div class="line"><span class="keyword">@end</span></div><div class="line"></div><div class="line"><span class="comment">//MyThread.m</span></div><div class="line"><span class="class"><span class="keyword">@implementation</span> <span class="title">MyThread</span></span></div><div class="line">- (<span class="keyword">void</span>)main &#123;</div><div class="line">    <span class="built_in">NSLog</span>(<span class="string">@"this is MyThread"</span>);</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">//main.m</span></div><div class="line"><span class="meta">#import <span class="meta-string">&lt;Foundation/Foundation.h&gt;</span></span></div><div class="line"><span class="meta">#import <span class="meta-string">"MyThread.h"</span></span></div><div class="line"></div><div class="line"><span class="keyword">int</span> main(<span class="keyword">int</span> argc, <span class="keyword">const</span> <span class="keyword">char</span> * argv[]) &#123;</div><div class="line">    <span class="keyword">@autoreleasepool</span> &#123;</div><div class="line">        MyThread * th = [[MyThread alloc] init];</div><div class="line">        [th start];</div><div class="line">        [[<span class="built_in">NSRunLoop</span> mainRunLoop] run];</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">return</span> <span class="number">0</span>;</div><div class="line">&#125;</div><div class="line"><span class="keyword">@end</span></div></pre></td></tr></table></figure>
</li>
<li><p>其他：NSObject中的方法</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">- (<span class="keyword">void</span>)performSelectorInBackground:(SEL)aSelector withObject:(<span class="keyword">id</span>)arg;</div></pre></td></tr></table></figure>
</li>
</ul>
<p>####线程的基本管理</p>
<ul>
<li>获取主线程<code>+ (NSThread *)mainThread</code></li>
<li>获取当前线程<code>+ (NSThread *)currentThread;</code></li>
<li>阻塞当前线程<code>+ (void)sleepUntilDate:(NSDate *)date;</code>和<code>+ (void)sleepForTimeInterval:(NSTimeInterval)ti;</code></li>
<li>销毁消除当前线程（currentThread）<code>+ (void)exit;</code></li>
<li>取消线程<code>- (void)cancel;</code>：将线程的状体置为cancelled，并不会停止线程的执行</li>
<li>线程键的通讯<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">- (<span class="keyword">void</span>)performSelectorOnMainThread:(SEL)aSelector withObject:(<span class="keyword">id</span>)arg waitUntilDone:(<span class="built_in">BOOL</span>)wait;</div><div class="line">- (<span class="keyword">void</span>)performSelector:(SEL)aSelector onThread:(<span class="built_in">NSThread</span> *)thr withObject:(<span class="keyword">id</span>)arg waitUntilDone:(<span class="built_in">BOOL</span>)wait;</div></pre></td></tr></table></figure>
</li>
</ul>
<p>###线程同步与互斥</p>
<p>####锁</p>
<ul>
<li><p>@synchronized（obj）对代码段进行加锁，同时只能一个线程访问该代码段</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">@synchronized</span>(<span class="keyword">self</span>) &#123;</div><div class="line">    i++;</div><div class="line">    <span class="built_in">NSLog</span>(<span class="string">@"%ld"</span>, i);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
<li><p>NSLock：与@synchronized类似</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="built_in">NSLock</span> * lock = [[<span class="built_in">NSLock</span> alloc] init];</div><div class="line"><span class="keyword">if</span> ([lock tryLock]) &#123;</div><div class="line">    [lock lock];</div><div class="line">    i++;</div><div class="line">    <span class="built_in">NSLog</span>(<span class="string">@"%ld"</span>, i);</div><div class="line">    [lock unlock];</div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
<li><p>NSConditionLock条件锁：在所的基础上添加了条件，只有满足对应的条件，才能打开相应的锁</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div></pre></td><td class="code"><pre><div class="line">- (<span class="keyword">void</span>)startTest &#123;</div><div class="line">    _conLock = [[<span class="built_in">NSConditionLock</span> alloc] init];</div><div class="line">    [<span class="built_in">NSThread</span> detachNewThreadSelector:<span class="keyword">@selector</span>(threadFun:) toTarget:<span class="keyword">self</span> withObject:<span class="string">@"top thread"</span>];</div><div class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">200</span>; i++) &#123;</div><div class="line">        [<span class="built_in">NSThread</span> detachNewThreadSelector:<span class="keyword">@selector</span>(threadFun2:) toTarget:<span class="keyword">self</span> withObject:@(i)];</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line">- (<span class="keyword">void</span>)threadFun:(<span class="keyword">id</span>)obj &#123;</div><div class="line"></div><div class="line">    [_conLock lock];</div><div class="line">    <span class="built_in">NSLog</span>(<span class="string">@"%@"</span>, obj);</div><div class="line">    [<span class="built_in">NSThread</span> sleepForTimeInterval:<span class="number">1.0</span>f];</div><div class="line">    <span class="comment">//加锁，条件为10</span></div><div class="line">    [_conLock unlockWithCondition:<span class="number">10</span>];</div><div class="line">&#125;</div><div class="line"></div><div class="line">- (<span class="keyword">void</span>)threadFun2:(<span class="keyword">id</span>)obj &#123;</div><div class="line">    <span class="built_in">NSInteger</span> value = [obj integerValue];</div><div class="line"></div><div class="line">    <span class="comment">//只有到value等于10时，才能成功加锁，否则阻塞</span></div><div class="line">    [_conLock lockWhenCondition:value];</div><div class="line">    <span class="built_in">NSLog</span>(<span class="string">@"thread%@"</span>, obj);</div><div class="line">    [<span class="built_in">NSThread</span> sleepForTimeInterval:<span class="number">1.0</span>f];</div><div class="line">    <span class="comment">//解锁，并把条件设为value + 3,则下次上锁的条件为13，一次类推13,16,19...</span></div><div class="line">    [_conLock unlockWithCondition:value + <span class="number">3</span>];</div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
</ul>
<p>输出结果：</p>
<p><img src="http://img.blog.csdn.net/20150410103408108" alt="这里写图片描述"></p>
<ul>
<li>NSRecursiveLock递归锁：同一个线程中，递归或多次调用加锁代码段，不会造成死锁<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line">j = <span class="number">0</span>;</div><div class="line">[<span class="built_in">NSThread</span> detachNewThreadSelector:<span class="keyword">@selector</span>(threadFun:) toTarget:<span class="keyword">self</span> withObject:<span class="string">@"top thread1"</span>];</div><div class="line">[<span class="built_in">NSThread</span> detachNewThreadSelector:<span class="keyword">@selector</span>(threadFun:) toTarget:<span class="keyword">self</span> withObject:<span class="string">@"top thread2"</span>];</div><div class="line"></div><div class="line">- (<span class="keyword">void</span>)threadFun:(<span class="keyword">id</span>)obj &#123;</div><div class="line">    [<span class="keyword">self</span> testWith:obj];</div><div class="line">&#125;</div><div class="line"></div><div class="line">- (<span class="keyword">void</span>)testWith:(<span class="keyword">id</span>)obj &#123;</div><div class="line">    [_recLock lock];</div><div class="line">    <span class="built_in">NSLog</span>(<span class="string">@"test recursive,thread:%@, lock:%ld"</span>, obj, j++);</div><div class="line">    [<span class="built_in">NSThread</span> sleepForTimeInterval:<span class="number">1.0</span>f];</div><div class="line">    <span class="keyword">if</span> (j &lt; <span class="number">10</span>) &#123;</div><div class="line">        [<span class="keyword">self</span> testWith:obj];</div><div class="line">    &#125;</div><div class="line">    [_recLock unlock];</div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
</ul>
<p>输出结果：</p>
<p><img src="http://img.blog.csdn.net/20150410104742410" alt="这里写图片描述"></p>
<ul>
<li>NSDistributedLock分布式锁：用于多个进程之间互斥访问资源，一般用于Mac开发</li>
</ul>
<p>####条件<br>使用NSCondition，可以实现多线程的同步，解决类似生产者消费者问题。<br><figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div></pre></td><td class="code"><pre><div class="line"><span class="meta">#import <span class="meta-string">"testThread.h"</span></span></div><div class="line"></div><div class="line"><span class="class"><span class="keyword">@implementation</span> <span class="title">testThread</span></span></div><div class="line">&#123;</div><div class="line">    <span class="built_in">NSInteger</span> i;</div><div class="line">    <span class="built_in">NSCondition</span> * _con;</div><div class="line">    <span class="built_in">NSMutableArray</span> * _products;</div><div class="line">&#125;</div><div class="line"></div><div class="line">- (<span class="keyword">void</span>)startTest &#123;</div><div class="line">    _con = [[<span class="built_in">NSCondition</span> alloc] init];</div><div class="line">    _products = [[<span class="built_in">NSMutableArray</span> alloc] init];</div><div class="line">    [<span class="built_in">NSThread</span> detachNewThreadSelector:<span class="keyword">@selector</span>(threadFun2:) toTarget:<span class="keyword">self</span> withObject:<span class="string">@"thread2"</span>];</div><div class="line">    [<span class="built_in">NSThread</span> detachNewThreadSelector:<span class="keyword">@selector</span>(threadFun2:) toTarget:<span class="keyword">self</span> withObject:<span class="string">@"thread3"</span>];</div><div class="line">    [<span class="built_in">NSThread</span> detachNewThreadSelector:<span class="keyword">@selector</span>(threadFun1:) toTarget:<span class="keyword">self</span> withObject:<span class="string">@"thread1"</span>];</div><div class="line">&#125;</div><div class="line"></div><div class="line">- (<span class="keyword">void</span>)threadFun1:(<span class="keyword">id</span>)obj &#123;</div><div class="line">    <span class="keyword">while</span> (<span class="number">1</span>) &#123;</div><div class="line">        [<span class="built_in">NSThread</span> sleepForTimeInterval:<span class="number">2.0</span>f];</div><div class="line">        [_products addObject:<span class="string">@"apple"</span>];<span class="comment">//生产者创造一个产品</span></div><div class="line">        <span class="built_in">NSLog</span>(<span class="string">@"%@ add one product, product count:%ld"</span>, obj, _products.count);</div><div class="line">        [_con signal];<span class="comment">//通知消费者，消费产品</span></div><div class="line"><span class="comment">//        [_con broadcast];</span></div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line">- (<span class="keyword">void</span>)threadFun2:(<span class="keyword">id</span>)obj &#123;</div><div class="line">    <span class="keyword">while</span> (<span class="number">1</span>) &#123;</div><div class="line">        [_con lock];</div><div class="line">        [_con wait];<span class="comment">//等待生产者的通知</span></div><div class="line">        [_products removeObjectAtIndex:<span class="number">0</span>];<span class="comment">//消费者消费一个产品</span></div><div class="line">        <span class="built_in">NSLog</span>(<span class="string">@"%@ remove one product, proudct count:%ld"</span>, obj, _products.count);</div><div class="line">        [_con unlock];</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="keyword">@end</span></div></pre></td></tr></table></figure></p>
<p>##GCD</p>
<p>###基本用法</p>
<p>####队列</p>
<ul>
<li>串行队列：同时只能执行一个任务<ul>
<li>所有任务都在同一个线程中执行，FIFO</li>
<li>多个串行队列之间是并行执行的，会占用多个线程</li>
<li>创建串行队列：<code>dispatch_queue_t serialQueue = dispatch_queue_create(&quot;myQueue&quot;, DISPATCH_QUEUE_SERIAL);</code></li>
<li><code>dispatch_get_main_queue();</code>获取主线程上的一个全局可用的串行队列</li>
</ul>
</li>
<li>并行队列：同时可以执行多个任务<ul>
<li>多个任务在不同的线程上执行，最大并发数（最多起的线程数）由操作系统根据当前的系统状态决定，不可手动设置（NSOperation可以）</li>
<li>创建并行队列：<code>dispatch_queue_t concurrentQueue = dispatch_queue_create(&quot;myQueue&quot;, DISPATCH_QUEUE_CONCURRENT);</code></li>
<li><code>dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);</code>获取一个全局可用的并行队列<br>####任务</li>
</ul>
</li>
<li><p>同步任务：添加一个任务后，需要等待任务执行完后才能返回</p>
<ul>
<li>无论是串行队列还是并行队列，同步任务都是在主线程上执行的</li>
<li>同步任务会阻塞当前线程</li>
<li>向主队列中添加同步任务会造成<strong>死锁</strong>，见死锁①</li>
<li>向串行队列中添加嵌套的同步任务会造成<strong>死锁</strong>，见死锁②<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//同步任务</span></div><div class="line"><span class="built_in">dispatch_sync</span>(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, <span class="number">0</span>), ^&#123;</div><div class="line">            [<span class="built_in">NSThread</span> sleepForTimeInterval:<span class="number">1.0</span>f];</div><div class="line">            <span class="comment">//先打印</span></div><div class="line">            <span class="built_in">NSLog</span>(<span class="string">@"thread:%@"</span>, [<span class="built_in">NSThread</span> currentThread]);</div><div class="line">        &#125;);</div><div class="line"><span class="built_in">NSLog</span>(<span class="string">@"haha"</span>);<span class="comment">//后打印</span></div><div class="line"></div><div class="line"><span class="comment">//死锁①</span></div><div class="line"><span class="built_in">dispatch_sync</span>(dispatch_get_main_queue(), ^&#123;</div><div class="line">            [<span class="built_in">NSThread</span> sleepForTimeInterval:<span class="number">1.0</span>f];</div><div class="line">            <span class="built_in">NSLog</span>(<span class="string">@"thread:%@"</span>, [<span class="built_in">NSThread</span> currentThread]);</div><div class="line">        &#125;);        </div><div class="line"><span class="built_in">NSLog</span>(<span class="string">@"haha"</span>);<span class="comment">//造成死锁，haha永远不会打印</span></div><div class="line"></div><div class="line"><span class="comment">//死锁②</span></div><div class="line"><span class="built_in">dispatch_queue_t</span> serialQueue = dispatch_queue_create(<span class="string">"myQueue"</span>, DISPATCH_QUEUE_SERIAL);</div><div class="line"><span class="built_in">dispatch_sync</span>(serialQueue, ^&#123;</div><div class="line">            <span class="built_in">NSLog</span>(<span class="string">@"thread1:%@"</span>, [<span class="built_in">NSThread</span> currentThread]);</div><div class="line">            <span class="built_in">dispatch_sync</span>(serialQueue, ^&#123;</div><div class="line">                <span class="built_in">NSLog</span>(<span class="string">@"thread2:%@"</span>, [<span class="built_in">NSThread</span> currentThread]);<span class="comment">//造成死锁，thread2永远不会打印</span></div><div class="line">            &#125;);</div><div class="line">        &#125;);</div></pre></td></tr></table></figure>
</li>
</ul>
</li>
<li><p>异步任务：添加一个任务后不需要等待任务执行完成</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//异步任务</span></div><div class="line"><span class="built_in">dispatch_async</span>(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, <span class="number">0</span>), ^&#123;</div><div class="line">            [<span class="built_in">NSThread</span> sleepForTimeInterval:<span class="number">1.0</span>f];</div><div class="line">            <span class="comment">//后打印</span></div><div class="line">            <span class="built_in">NSLog</span>(<span class="string">@"thread:%@"</span>, [<span class="built_in">NSThread</span> currentThread]);</div><div class="line">        &#125;);</div><div class="line"><span class="built_in">NSLog</span>(<span class="string">@"haha"</span>);<span class="comment">//先打印</span></div></pre></td></tr></table></figure>
</li>
</ul>
<p>###其他用法</p>
<ul>
<li><p>dispatch_after：延迟指定的时间后，将任务添加到指定的队列中</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(<span class="number">10.0</span>f * <span class="built_in">NSEC_PER_SEC</span>));</div><div class="line">dispatch_after(time, dispatch_get_main_queue(), ^&#123;</div><div class="line">    <span class="built_in">NSLog</span>(<span class="string">@"haha"</span>);</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
</li>
<li><p>dispatch_group：将多个任务或队列归为一组，在这组的所有任务都执行完之后再执行后面的操作</p>
<ul>
<li>dispatch_group_async函数：创建一个指定队列中的异步任务，并将其添加到指定组中</li>
<li>dispatch_group_notify函数：指定组中所有任务都执行完后，会执行该函数所指定的的任务</li>
<li>dispatch_group_wait函数：阻塞当前线程，等待group中所有任务执行完毕<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//使用dispatch_group_notify</span></div><div class="line">dispatch_group_t group = dispatch_group_create();</div><div class="line"><span class="built_in">dispatch_queue_t</span> concurrentQueue = dispatch_queue_create(<span class="string">"myQueue"</span>, DISPATCH_QUEUE_CONCURRENT);</div><div class="line">dispatch_group_async(group, concurrentQueue, ^&#123;</div><div class="line">    <span class="built_in">NSLog</span>(<span class="string">@"1"</span>);</div><div class="line">    [<span class="built_in">NSThread</span> sleepForTimeInterval:<span class="number">1.0</span>f];</div><div class="line">&#125;);</div><div class="line">dispatch_group_async(group, concurrentQueue, ^&#123;</div><div class="line">    <span class="built_in">NSLog</span>(<span class="string">@"2"</span>);</div><div class="line">    [<span class="built_in">NSThread</span> sleepForTimeInterval:<span class="number">1.0</span>f];</div><div class="line">&#125;);</div><div class="line">dispatch_group_async(group, concurrentQueue, ^&#123;</div><div class="line">    <span class="built_in">NSLog</span>(<span class="string">@"3"</span>);</div><div class="line">    [<span class="built_in">NSThread</span> sleepForTimeInterval:<span class="number">1.0</span>f];</div><div class="line">&#125;);</div><div class="line">dispatch_group_async(group, concurrentQueue, ^&#123;</div><div class="line">    <span class="built_in">NSLog</span>(<span class="string">@"4"</span>);</div><div class="line">    [<span class="built_in">NSThread</span> sleepForTimeInterval:<span class="number">1.0</span>f];</div><div class="line">&#125;);</div><div class="line"></div><div class="line">dispatch_group_notify(group, concurrentQueue, ^&#123;</div><div class="line">    <span class="built_in">NSLog</span>(<span class="string">@"5"</span>);<span class="comment">//"1234"全部打印后，才会打印5</span></div><div class="line">&#125;);</div><div class="line"></div><div class="line"><span class="comment">//使用dispatch_group_wait</span></div><div class="line">dispatch_group_t group = dispatch_group_create();</div><div class="line"><span class="built_in">dispatch_queue_t</span> concurrentQueue = dispatch_queue_create(<span class="string">"myQueue"</span>, DISPATCH_QUEUE_CONCURRENT);</div><div class="line">dispatch_group_async(group, concurrentQueue, ^&#123;</div><div class="line">    <span class="built_in">NSLog</span>(<span class="string">@"1"</span>);</div><div class="line">    [<span class="built_in">NSThread</span> sleepForTimeInterval:<span class="number">1.0</span>f];</div><div class="line">&#125;);</div><div class="line">dispatch_group_async(group, concurrentQueue, ^&#123;</div><div class="line">    <span class="built_in">NSLog</span>(<span class="string">@"2"</span>);</div><div class="line">    [<span class="built_in">NSThread</span> sleepForTimeInterval:<span class="number">1.0</span>f];</div><div class="line">&#125;);</div><div class="line">dispatch_group_async(group, concurrentQueue, ^&#123;</div><div class="line">    <span class="built_in">NSLog</span>(<span class="string">@"3"</span>);</div><div class="line">    [<span class="built_in">NSThread</span> sleepForTimeInterval:<span class="number">1.0</span>f];</div><div class="line">&#125;);</div><div class="line">dispatch_group_async(group, concurrentQueue, ^&#123;</div><div class="line">    <span class="built_in">NSLog</span>(<span class="string">@"4"</span>);</div><div class="line">    [<span class="built_in">NSThread</span> sleepForTimeInterval:<span class="number">1.0</span>f];</div><div class="line">&#125;);</div><div class="line"></div><div class="line">dispatch_group_wait(group, DISPATCH_TIME_FOREVER);</div><div class="line"></div><div class="line"><span class="built_in">NSLog</span>(<span class="string">@"haha"</span>);<span class="comment">//"dispatch_group_wait"会阻塞线程，所有haha会在"1234"之后打印</span></div></pre></td></tr></table></figure>
</li>
</ul>
</li>
<li><p>diapatch_once：执行一次</p>
</li>
<li><p>dispatch_apply：按照指定的次数将指定的Block追加到指定的DispatchQueue中，并等待全部处理执行结束</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">dispatch_apply(<span class="number">10</span>, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, <span class="number">0</span>), ^(size_t t) &#123;</div><div class="line">    <span class="built_in">NSLog</span>(<span class="string">@"%zu"</span>, t);</div><div class="line">    [<span class="built_in">NSThread</span> sleepForTimeInterval:<span class="number">1.0</span>f];</div><div class="line">&#125;);</div><div class="line"><span class="built_in">NSLog</span>(<span class="string">@"haha"</span>);<span class="comment">//等待dispatch_apply中的所有任务都执行完之后才会带引"haha"</span></div></pre></td></tr></table></figure>
</li>
<li><p>dispatch_suspend / dispatch_resume</p>
<ul>
<li>dispatch_suspend：挂起指定的队列</li>
<li>dispatch_resume：恢复指定的队列</li>
</ul>
</li>
<li>Dispatch Semaphore：信号量，用于排他控制<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line">dispatch_semaphore_t semaphore = dispatch_semaphore_create(<span class="number">1</span>);</div><div class="line"></div><div class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">10</span>; i++) &#123;</div><div class="line">    <span class="built_in">dispatch_async</span>(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, <span class="number">0</span>), ^&#123;</div><div class="line"></div><div class="line">        <span class="keyword">long</span> result = dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);</div><div class="line">        <span class="comment">//排他，同时只能有一个线程进入这个代码块，相当于锁</span></div><div class="line">        <span class="built_in">NSLog</span>(<span class="string">@"end wait, result:%ld"</span>, result);</div><div class="line">        [<span class="built_in">NSThread</span> sleepForTimeInterval:<span class="number">1.0</span>f];</div><div class="line"></div><div class="line">        dispatch_semaphore_signal(semaphore);</div><div class="line">    &#125;);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
</ul>
<p>##NSOperation</p>
<p>###基本用法</p>
<ul>
<li><p>NSBlockOperation：以Block的形式定义任务</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">@interface</span> <span class="title">testOperation</span> ()</span></div><div class="line"><span class="keyword">@property</span> (<span class="keyword">nonatomic</span>, <span class="keyword">strong</span>) <span class="built_in">NSOperationQueue</span> * queue;</div><div class="line"><span class="keyword">@end</span></div><div class="line"></div><div class="line"><span class="class"><span class="keyword">@implementation</span> <span class="title">testOperation</span></span></div><div class="line"></div><div class="line">- (<span class="keyword">void</span>)startTest &#123;</div><div class="line"></div><div class="line">    <span class="comment">//创建操作</span></div><div class="line">    <span class="built_in">NSOperation</span> * oper1 = [<span class="built_in">NSBlockOperation</span> blockOperationWithBlock:^&#123;</div><div class="line">        <span class="built_in">NSLog</span>(<span class="string">@"test block operation1, current thread:%@"</span>, [<span class="built_in">NSThread</span> currentThread]);</div><div class="line">        [<span class="built_in">NSThread</span> sleepForTimeInterval:<span class="number">1.0</span>f];</div><div class="line">    &#125;];</div><div class="line"></div><div class="line">    <span class="built_in">NSOperation</span> * oper2 = [<span class="built_in">NSBlockOperation</span> blockOperationWithBlock:^&#123;</div><div class="line">        <span class="built_in">NSLog</span>(<span class="string">@"test block operation2, current thread:%@"</span>, [<span class="built_in">NSThread</span> currentThread]);</div><div class="line">        [<span class="built_in">NSThread</span> sleepForTimeInterval:<span class="number">1.0</span>f];</div><div class="line">    &#125;];</div><div class="line"></div><div class="line">    <span class="built_in">NSOperation</span> * oper3 = [<span class="built_in">NSBlockOperation</span> blockOperationWithBlock:^&#123;</div><div class="line">        <span class="built_in">NSLog</span>(<span class="string">@"test block operation3, current thread:%@"</span>, [<span class="built_in">NSThread</span> currentThread]);</div><div class="line">        [<span class="built_in">NSThread</span> sleepForTimeInterval:<span class="number">1.0</span>f];</div><div class="line">    &#125;];</div><div class="line"></div><div class="line">    <span class="built_in">NSOperation</span> * oper4 = [<span class="built_in">NSBlockOperation</span> blockOperationWithBlock:^&#123;</div><div class="line">        <span class="built_in">NSLog</span>(<span class="string">@"test block operation4, current thread:%@"</span>, [<span class="built_in">NSThread</span> currentThread]);</div><div class="line">        [<span class="built_in">NSThread</span> sleepForTimeInterval:<span class="number">1.0</span>f];</div><div class="line">    &#125;];</div><div class="line"></div><div class="line">    <span class="keyword">self</span>.queue = [[<span class="built_in">NSOperationQueue</span> alloc] init];</div><div class="line">    <span class="comment">//将操作加入队列中，操作就会在队列中并发执行，NSOperationQueue默认是并发队列</span></div><div class="line">    [<span class="keyword">self</span>.queue addOperation:oper1];</div><div class="line">    [<span class="keyword">self</span>.queue addOperation:oper2];</div><div class="line">    [<span class="keyword">self</span>.queue addOperation:oper3];</div><div class="line">    [<span class="keyword">self</span>.queue addOperation:oper4];</div><div class="line">&#125;</div><div class="line"><span class="keyword">@end</span></div></pre></td></tr></table></figure>
</li>
<li><p>NSInvocationOperation</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">@interface</span> <span class="title">testOperation</span> ()</span></div><div class="line"><span class="keyword">@property</span> (<span class="keyword">nonatomic</span>, <span class="keyword">strong</span>) <span class="built_in">NSOperationQueue</span> * queue;</div><div class="line"><span class="keyword">@end</span></div><div class="line"></div><div class="line"><span class="class"><span class="keyword">@implementation</span> <span class="title">testOperation</span></span></div><div class="line"></div><div class="line">- (<span class="keyword">void</span>)startTest &#123;</div><div class="line"></div><div class="line">    <span class="built_in">NSMethodSignature</span> * sig = [[<span class="keyword">self</span> <span class="keyword">class</span>] instanceMethodSignatureForSelector:<span class="keyword">@selector</span>(oper1Fun:andObj2:)];</div><div class="line">    <span class="built_in">NSInvocation</span> * invo = [<span class="built_in">NSInvocation</span> invocationWithMethodSignature:sig];</div><div class="line">    [invo setTarget:<span class="keyword">self</span>];</div><div class="line">    [invo setSelector:<span class="keyword">@selector</span>(oper1Fun:andObj2:)];</div><div class="line">    <span class="built_in">NSString</span> * arg1 = <span class="string">@"haha"</span>;</div><div class="line">    <span class="built_in">NSString</span> * arg2 = <span class="string">@"oooo"</span>;</div><div class="line">    [invo setArgument:&amp;arg1 atIndex:<span class="number">2</span>];</div><div class="line">    [invo setArgument:&amp;arg2 atIndex:<span class="number">3</span>];</div><div class="line">    <span class="built_in">NSOperation</span> * oper1 = [[<span class="built_in">NSInvocationOperation</span> alloc] initWithInvocation:invo];</div><div class="line"></div><div class="line">    <span class="built_in">NSOperation</span> * oper2 = [[<span class="built_in">NSInvocationOperation</span> alloc] initWithTarget:<span class="keyword">self</span> selector:<span class="keyword">@selector</span>(oper2Fun) object:<span class="literal">nil</span>];</div><div class="line"></div><div class="line">    <span class="keyword">self</span>.queue = [[<span class="built_in">NSOperationQueue</span> alloc] init];</div><div class="line">    [<span class="keyword">self</span>.queue addOperation:oper1];</div><div class="line">    [<span class="keyword">self</span>.queue addOperation:oper2];</div><div class="line">&#125;</div><div class="line"></div><div class="line">- (<span class="keyword">void</span>)oper1Fun:(<span class="keyword">id</span>)obj1 andObj2:(<span class="keyword">id</span>)obj2 &#123;</div><div class="line">    <span class="built_in">NSLog</span>(<span class="string">@"test invocation operation1, current thread:%@, obj1:%@, obj2:%@"</span>, [<span class="built_in">NSThread</span> currentThread], obj1, obj2);</div><div class="line">    [<span class="built_in">NSThread</span> sleepForTimeInterval:<span class="number">1.0</span>f];</div><div class="line">&#125;</div><div class="line"></div><div class="line">- (<span class="keyword">void</span>)oper2Fun &#123;</div><div class="line">    <span class="built_in">NSLog</span>(<span class="string">@"test invocation operation2, current thread:%@"</span>, [<span class="built_in">NSThread</span> currentThread]);</div><div class="line">&#125;</div><div class="line"><span class="keyword">@end</span></div></pre></td></tr></table></figure>
</li>
<li><p>继承NSOperation，重写main方法</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">@interface</span> <span class="title">MyOperation</span> : <span class="title">NSOperation</span></span></div><div class="line"><span class="keyword">@end</span></div><div class="line"></div><div class="line"><span class="class"><span class="keyword">@implementation</span> <span class="title">MyOperation</span></span></div><div class="line">- (<span class="keyword">void</span>)main &#123;</div><div class="line">    <span class="built_in">NSLog</span>(<span class="string">@"MyOperation, current thread:%@"</span>, [<span class="built_in">NSThread</span> currentThread]);</div><div class="line">    [<span class="built_in">NSThread</span> sleepForTimeInterval:<span class="number">1.0</span>f];</div><div class="line">&#125;</div><div class="line"><span class="keyword">@end</span></div><div class="line"></div><div class="line"><span class="comment">//main.m</span></div><div class="line"><span class="built_in">NSOperationQueue</span> * queue = [[<span class="built_in">NSOperationQueue</span> alloc] init];</div><div class="line"></div><div class="line">MyOperation * op1 = [[MyOperation alloc] init];</div><div class="line">MyOperation * op2 = [[MyOperation alloc] init];</div><div class="line">MyOperation * op3 = [[MyOperation alloc] init];</div><div class="line">MyOperation * op4 = [[MyOperation alloc] init];</div><div class="line">MyOperation * op5 = [[MyOperation alloc] init];</div><div class="line">MyOperation * op6 = [[MyOperation alloc] init];</div><div class="line"></div><div class="line">[queue addOperation:op1];</div><div class="line">[queue addOperation:op2];</div><div class="line">[queue addOperation:op3];</div><div class="line">[queue addOperation:op4];</div><div class="line">[queue addOperation:op5];</div><div class="line">[queue addOperation:op6];</div></pre></td></tr></table></figure>
</li>
</ul>
<p>###其他用法</p>
<ul>
<li>设置最大并发数<br><code>self.queue.maxConcurrentOperationCount = 3;</code></li>
<li>设置操作之间的依赖关系<br><code>[oper2 addDependency:oper1];//oper2依赖于oper1，即必须oper1执行完之后才能执行oper2</code></li>
<li>手动管理NSOperation<ul>
<li>运行一个Operation：<code>- (void)start;</code>默认的start方法会直接进行一些异常判断，然后直接调用<code>- (void)main;</code></li>
<li>取消一个Operation：<code>- (void)cancel;</code>调用cancel方法并不会停止操作的执行，这取决于main方法中对cancel的处理。如果在main方法中没有对cancel进行处理，发送cancel消息是没有任何效果的<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//MyOperation.m</span></div><div class="line"><span class="class"><span class="keyword">@implementation</span> <span class="title">MyOperation</span></span></div><div class="line"></div><div class="line">- (<span class="keyword">void</span>)start &#123;</div><div class="line">    [<span class="built_in">NSThread</span> detachNewThreadSelector:<span class="keyword">@selector</span>(main) toTarget:<span class="keyword">self</span> withObject:<span class="literal">nil</span>];</div><div class="line">&#125;</div><div class="line"></div><div class="line">- (<span class="keyword">void</span>)main &#123;</div><div class="line">    <span class="built_in">NSInteger</span> index = <span class="number">0</span>;</div><div class="line">    <span class="keyword">while</span> (<span class="number">1</span>) &#123;</div><div class="line">        <span class="built_in">NSLog</span>(<span class="string">@"current thread:%@, index:%ld"</span>, [<span class="built_in">NSThread</span> currentThread], index++);</div><div class="line">        <span class="keyword">if</span> (<span class="keyword">self</span>.isCancelled) &#123;</div><div class="line">            <span class="built_in">NSLog</span>(<span class="string">@"cancel"</span>);</div><div class="line">            <span class="keyword">return</span>;</div><div class="line">        &#125;</div><div class="line">        [<span class="built_in">NSThread</span> sleepForTimeInterval:<span class="number">1.0</span>f];</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"><span class="keyword">@end</span></div><div class="line"></div><div class="line"><span class="comment">//main.m</span></div><div class="line">MyOperation * op1 = [[MyOperation alloc] init];</div><div class="line">[op1 start];</div><div class="line">[<span class="built_in">NSThread</span> sleepForTimeInterval:<span class="number">3.0</span>f];</div><div class="line">[op1 cancel];</div></pre></td></tr></table></figure>
</li>
</ul>
</li>
</ul>

      
    </div>

    <div>
      
        
      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2015/10/04/iOS中Emoji表情的判断/" rel="next" title="iOS中Emoji表情的判断">
                <i class="fa fa-chevron-left"></i> iOS中Emoji表情的判断
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2015/10/04/iOS中的富文本技术(1)TextKit简介/" rel="prev" title="iOS中的富文本技术(1)TextKit简介">
                iOS中的富文本技术(1)TextKit简介 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div class="ds-thread" data-thread-key="2015/10/04/iOS中的多线程编程/"
           data-title="iOS中的多线程编程" data-url="http://yoursite.com/2015/10/04/iOS中的多线程编程/">
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/smallhead.png"
               alt="liujinlongxa" />
          <p class="site-author-name" itemprop="name">liujinlongxa</p>
          <p class="site-description motion-element" itemprop="description">生命永不息，Coding永不止</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">31</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">3</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">3</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/liujinlongxa" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/JaylonLiu" target="_blank" title="Twitter">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  Twitter
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/u/1523828165/home" target="_blank" title="微博">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  微博
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.douban.com/people/2470188/" target="_blank" title="豆瓣">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  豆瓣
                </a>
              </span>
            
          
        </div>

        
        

        
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <p class="post-toc-empty">此文章未包含目录</p>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2016</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">liujinlongxa</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" href="http://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.0.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"liujinlongxa"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
  






  
  
  

  

  

</body>
</html>
